﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using System.Data;
using BLL;

public partial class guanzhu : WeiPage
{
    PersonInfoBO pbo = new PersonInfoBO();
    WeiXinRequestBO wbo = new WeiXinRequestBO();
    protected void Page_Load(object sender, EventArgs e)
    {
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        dt.Columns.Add("nickname");
        dt.Columns.Add("Name");
        dt.Columns.Add("Phone");
        dt.Columns.Add("sex");
        dt.Columns.Add("subscribe_time");
        dt.Columns.Add("Status");
        string access_token = Token();
        string url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + access_token;
        string returnmes = PostRequestGet(url);
        //Response.Write(returnmes);
        Data data = JsonConvert.DeserializeObject<Data>(returnmes);
        for (int i = 0; i < data.data.openid.Length; i++)
        {
            string info = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_token + "&openid=" + data.data.openid[i] + "&lang=zh_CN";
            string infomes = PostRequestGet(info);
            Info winfo = JsonConvert.DeserializeObject<Info>(infomes);


            DataRow row = dt.NewRow();
            row["nickname"] = winfo.nickname;
            row["sex"] = winfo.sex;
            if (winfo.sex.Equals("1"))
            {
                row["sex"] = "男";
            }
            else
            {
                row["sex"] = "女";
            }
            row["subscribe_time"] = UnixTimeToTime(winfo.subscribe_time);

            DataSet wxset = wbo.GetStatus(winfo.openid);
            if (wxset != null && wxset.Tables[0] != null && wxset.Tables[0].Rows.Count > 0)
            {
                DataRow dr = wxset.Tables[0].Rows[0];
                DateTime time = UnixTimeToTime(dr[3].ToString());
                DateTime now = DateTime.Now;
                double cha = (now.Day - time.Day) * 24 + (now.Hour - time.Hour) + (now.Minute - time.Minute) * 0.01 + (now.Second - time.Second) * 0.001;
                if (cha < 48)
                {
                    row["Status"] = "可对话";
                }
                else
                {
                    row["Status"] = "不可对话";
                }

            }
            else
            {
                row["Status"] = "不可对话";
            }

            DataSet set = pbo.GetNameByFromUserName(winfo.openid);
            if (set != null && set.Tables[0] != null && set.Tables[0].Rows.Count > 0)
            {
                DataRow dr = set.Tables[0].Rows[0];
                string name = dr[1].ToString();
                string phone = dr[3].ToString();
                //colname.ColumnName = set.Tables[0].Columns["Name"].ColumnName.ToString();
                //colphone.ColumnName = set.Tables[0].Columns["Phone"].ColumnName.ToString();
                //dt.Columns.Add(colname.ColumnName);
                //dt.Columns.Add(colphone.ColumnName); 

                row["Name"] = name;
                row["Phone"] = phone;

            }
            else
            {
                row["Name"] = "该用户未注册或绑定";
                row["Phone"] = "";
            }
            dt.Rows.Add(row);

        }

        dt.DefaultView.Sort = "subscribe_time desc";
        DataTable dtTemp = dt.DefaultView.ToTable();
        ds.Tables.Add(dtTemp);
        GridView1.DataSource = ds;
        GridView1.DataBind();


        //Response.Write(data.data.openid.Count);
        //Product product = new Product();
        //product.Name = "Apple";
        //product.Expiry = new DateTime(2008, 12, 28);
        ////product.Sizes = new string[] { "Small" };
        //product.Sizes = new Mod();
        //product.Sizes.openid = "222";
        //product.Sizes.hehe = new List<string>() { "hjahahhas", "jsjsjjs" };
        //string json = JsonConvert.SerializeObject(product);
        //Response.Write(json);
    }


    class Data
    {
        public string total;
        public string count;
        public Model data;
        public string next_openid;

    }

    class Model
    {
        //public List<string> openid;
        public string[] openid;
    }


    class Info
    {
        public int subscribe;
        public string openid;
        public string nickname;
        public string sex;
        public string language;
        public string city;
        public string province;
        public string country;
        public string headimgurl;
        public string subscribe_time;

    }

    /// <summary>
    /// unix时间转换为datetime
    /// </summary>
    /// <param name="timeStamp"></param>
    /// <returns></returns>
    private DateTime UnixTimeToTime(string timeStamp)
    {
        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
        long lTime = long.Parse(timeStamp + "0000000");
        TimeSpan toNow = new TimeSpan(lTime);
        return dtStart.Add(toNow);
    }


    // class Product {
    //    public string Name;
    //    public DateTime Expiry;
    //    public Mod  Sizes;

    //}
    //    class Mod
    //    {
    //        public string openid;
    //        public List<string> hehe;
    //    }

    //发送GET请求
    public string PostRequestGet(string url)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method = "GET";  //定义请求对象，并设置好请求URL地址      
        //request.ProtocolVersion = HttpVersion.Version10;
        //request.ContentType = "image/jpg";
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();    //定义响应对象，request在调用GetResponse方法事执行请求了，而不是在HttpWebRequest.Create的时候执行。
        //response.ContentType = "image/jpg";
        Stream stream = response.GetResponseStream(); //定义一个流对象，来获取响应流
        StreamReader sr = new StreamReader(stream, Encoding.UTF8);  //定义一个流读取对象，读取响应流
        string responseHTML = sr.ReadToEnd();
        return responseHTML;
    }
}